import { isObjectValueEqual } from "_commonFn/object"
import { getWebVersion } from "../../network/request"
import { Dialog } from 'vant'
import { getQueryStr } from "../common/url"
import store from '_store/store'

// 检测页面缓存数据是否为当前页面的数据，是则返回数据，否则返回false
export const checkCacheaIsPageData = ({
    sessionStorageKey,
    pageQueryStr,
    callback
}) => {
    if (typeof callback === 'function' && sessionStorageKey && typeof pageQueryStr === 'object') {
        let cache = sessionStorage.getItem(sessionStorageKey)
        if (cache) {
            cache = JSON.parse(cache)
            // console.log('cache', cache)
            const thisQuery = {...pageQueryStr}
            const cacheQuery = {...cache.queryStr}
            delete thisQuery.shareUser
            delete cacheQuery.shareUser
            // console.log('thisQuery', thisQuery)
            // console.log('cacheQuery', cacheQuery)
            if (isObjectValueEqual(thisQuery, cacheQuery)) {
                // console.log('缓存的数据所属页面与当前页面一致')
                callback(cache)
                return
            } else {
                // console.log('不是同一个页面')
                sessionStorage.removeItem(sessionStorageKey)
            }
        } else {
            callback(false)
        }
    }
}

export const checkIsNewPage = () => {
    if (process.env.IS_LOCAL === 0) {
        getWebVersion(version => {
            if (JSON.stringify(version) != JSON.stringify(process.env.VERSION)) {
                const now = new Date().getTime()
                if (store.state.showUpDataTime === 0 || (now - store.state.showUpDataTime) > 120000) {
                    store.commit('setUpDataTime', now)
                    Dialog.alert({
                        message: '尊敬的用户，您正在浏览的页面已更新，请点击下方"更新页面"按钮,即可查看最新页面！',
                        confirmButtonText: '更新页面',
                        closeOnClickOverlay: true,
                    })
                    .then(() => { // 点击更新页面
                        const url = location.href.split('#')[0]
                        const updataStr = `updata=${now}`
                        const isHadQueryStr = Object.keys(getQueryStr()).length > 0
                        const line = isHadQueryStr ? `&` : '?'
                        window.location.replace(`${url}${line}${updataStr}`)
                    })
                }
            }
        })
    }
}